const blogType = require("../dao/blogTypeDao");
const validate = require("validate.js");
const { handleDataArr } = require("../utils/tool");
const { ValidationError } = require("../utils/errors");
//添加文章分类
const addBlogType = async (typeInfo) => {
  //数据验证
  const rule = {
    name: {
      presence: {
        allowEmpty: false,
      },
      type: "string",
    },
    order: {
      presence: {
        allowEmpty: false,
      },
      type: "integer",
    },
  };
  const result = validate.validate(typeInfo, rule);
  if (!result) {
    //验证通过
    typeInfo.articleCount = 0; //新建分类文章数量默认为0
    const data = await blogType.addBlogType(typeInfo);
    return data.toJSON();
  }
  throw new ValidationError("数据验证失败");
};

//删除文章分类
const deleteBlogType = async (id) => {
  return await blogType.deleteBlogType(id);
};

//修改文章分类
const updateBlogType = async (id, type) => {
  //数据验证
  const rule = {
    name: {
      type: "string",
    },
    order: {
      type: "number",
    },
  };
  const result = validate.validate(type, rule);
  if (!result) {
    const data = await blogType.updateBlogType(id, type);
    return data.toJSON();
  }
  throw new ValidationError("数据验证失败");
};

//获取单个文章分类
const oneBlogType = async (id) => {
  const data = await blogType.oneBlogType(id);
  return data.toJSON();
};

//获取所有文章分类
const getAllBlogType = async () => {
  const data = handleDataArr(await blogType.getAllBlogType());
  //根据order排序
  data.sort((a, b) => {
    return a.order - b.order;
  });
  return data;
};

module.exports = {
  addBlogType,
  deleteBlogType,
  updateBlogType,
  oneBlogType,
  getAllBlogType,
};
